package net.suncaper.psychological.utils;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import net.suncaper.psychological.model.domain.CaseReport;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.time.format.DateTimeFormatter;

/**
 * Word文档导出工具类
 */
public class WordExportUtil {
    
    /**
     * 生成结案报告Word文档
     */
    public static byte[] generateCaseReportWord(CaseReport caseReport) throws IOException {
        XWPFDocument document = new XWPFDocument();
        
        // 设置页面为A4
        CTSectPr sectPr = document.getDocument().getBody().isSetSectPr() ? 
            document.getDocument().getBody().getSectPr() : 
            document.getDocument().getBody().addNewSectPr();
        CTPageMar pageMar = sectPr.isSetPgMar() ? sectPr.getPgMar() : sectPr.addNewPgMar();
        pageMar.setLeft(BigInteger.valueOf(1440L)); // 1 inch = 1440 twips
        pageMar.setRight(BigInteger.valueOf(1440L));
        pageMar.setTop(BigInteger.valueOf(1440L));
        pageMar.setBottom(BigInteger.valueOf(1440L));
        
        // 标题
        XWPFParagraph titleParagraph = document.createParagraph();
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleRun = titleParagraph.createRun();
        titleRun.setText("心理咨询结案报告");
        titleRun.setBold(true);
        titleRun.setFontSize(18);
        titleRun.setFontFamily("宋体");
        
        // 添加空行
        document.createParagraph();
        
        // 创建表格
        XWPFTable table = document.createTable(8, 2);
        table.setWidth("100%");
        
        // 设置表格样式
        CTTblPr tblPr = table.getCTTbl().getTblPr();
        CTTblBorders borders = tblPr.addNewTblBorders();
        borders.addNewTop().setVal(STBorder.SINGLE);
        borders.addNewBottom().setVal(STBorder.SINGLE);
        borders.addNewLeft().setVal(STBorder.SINGLE);
        borders.addNewRight().setVal(STBorder.SINGLE);
        borders.addNewInsideH().setVal(STBorder.SINGLE);
        borders.addNewInsideV().setVal(STBorder.SINGLE);
        
        // 填充表格内容
        fillTableRow(table, 0, "来访者学号", caseReport.getStudentId() != null ? caseReport.getStudentId().toString() : "");
        fillTableRow(table, 1, "来访者姓名", caseReport.getName() != null ? caseReport.getName() : "");
        fillTableRow(table, 2, "来访者性别", getGenderText(caseReport.getGender()));
        fillTableRow(table, 3, "来访者院系", caseReport.getDepartment() != null ? caseReport.getDepartment() : "");
        fillTableRow(table, 4, "来访者联系电话", caseReport.getPhone() != null ? caseReport.getPhone() : "");
        fillTableRow(table, 5, "问题类型", caseReport.getProblemType() != null ? caseReport.getProblemType() : "");
        fillTableRow(table, 6, "咨询总次数", caseReport.getTotalSessions() != null ? caseReport.getTotalSessions().toString() : "");
        
        // 咨询效果自评（可能需要跨行）
        XWPFTableRow row7 = table.getRow(7);
        XWPFTableCell cell7_0 = row7.getCell(0);
        XWPFTableCell cell7_1 = row7.getCell(1);
        
        XWPFParagraph p7_0 = cell7_0.getParagraphs().get(0);
        XWPFRun run7_0 = p7_0.createRun();
        run7_0.setText("咨询效果自评");
        run7_0.setBold(true);
        run7_0.setFontSize(12);
        run7_0.setFontFamily("宋体");
        
        XWPFParagraph p7_1 = cell7_1.getParagraphs().get(0);
        XWPFRun run7_1 = p7_1.createRun();
        run7_1.setText(caseReport.getSelfEvaluation() != null ? caseReport.getSelfEvaluation() : "");
        run7_1.setFontSize(12);
        run7_1.setFontFamily("宋体");
        
        // 设置单元格高度 - 使用更简单的方法
        // 通过添加多个空行来增加单元格高度
        for (int i = 0; i < 5; i++) {
            XWPFParagraph emptyPara = cell7_1.addParagraph();
            XWPFRun emptyRun = emptyPara.createRun();
            emptyRun.setText("");
        }
        
        // 添加空行
        document.createParagraph();
        
        // 添加生成时间
        XWPFParagraph timeParagraph = document.createParagraph();
        timeParagraph.setAlignment(ParagraphAlignment.RIGHT);
        XWPFRun timeRun = timeParagraph.createRun();
        timeRun.setText("生成时间：" + (caseReport.getCreatedAt() != null ? 
            caseReport.getCreatedAt().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss")) : 
            java.time.LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss"))));
        timeRun.setFontSize(10);
        timeRun.setFontFamily("宋体");
        timeRun.setColor("666666");
        
        // 转换为字节数组
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        document.write(outputStream);
        document.close();
        
        return outputStream.toByteArray();
    }
    
    /**
     * 填充表格行
     */
    private static void fillTableRow(XWPFTable table, int rowIndex, String label, String value) {
        XWPFTableRow row = table.getRow(rowIndex);
        XWPFTableCell cell0 = row.getCell(0);
        XWPFTableCell cell1 = row.getCell(1);
        
        // 设置标签
        XWPFParagraph p0 = cell0.getParagraphs().get(0);
        XWPFRun run0 = p0.createRun();
        run0.setText(label);
        run0.setBold(true);
        run0.setFontSize(12);
        run0.setFontFamily("宋体");
        
        // 设置值
        XWPFParagraph p1 = cell1.getParagraphs().get(0);
        XWPFRun run1 = p1.createRun();
        run1.setText(value);
        run1.setFontSize(12);
        run1.setFontFamily("宋体");
    }
    
    /**
     * 获取性别文本
     */
    private static String getGenderText(String gender) {
        if ("M".equals(gender)) {
            return "男";
        } else if ("F".equals(gender)) {
            return "女";
        }
        return gender != null ? gender : "";
    }
} 